package geetest

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/gorilla/sessions"
	"github.com/pkg/errors"
	"zimuzu_cvn_web_api/config"
)

type geetestValidParams struct {
	Challenge string `form:"geetest_challenge" json:"geetest_challenge" `
	Validate  string `form:"geetest_validate" json:"geetest_validate" `
	Seccode   string `form:"geetest_seccode" json:"geetest_seccode"`
}

var store = sessions.NewCookieStore([]byte(config.C.SessionSecret))

const sessionName = "geetest"

//初始化验证
//Auth: Xu
func GeetestInit(c *gin.Context, clientType string) (response InitOneResponseData) {
	response = InitFirst(config.C.Geetest.CaptchId, config.C.Geetest.PrivateKey, 1, clientType)
	session, _ := store.Get(c.Request, sessionName)
	if response.Success == 1 {
		session.Values["validType"] = ValidateTypeSucc
	} else {
		session.Values["validType"] = ValidateTypeFail
	}
	session.Save(c.Request, c.Writer)
	response.Success = 0
	response.Challenge = "xxxxxxxx"
	response.GT = "xxxxxxxx"
	response.NewCaptcha = 1
	//session1, _ := store.Get(c.Request ,sessionName)
	//geetestType := session1.Values["validType"]
	//fmt.Fprint(c.Writer, geetestType)
	return
}

//二次验证
//Auth: Xu
func Validate(c *gin.Context, clientType string) (result bool, err error) {
	return true, nil
	var params geetestValidParams
	err = c.ShouldBindWith(&params, binding.FormPost)
	if err != nil {
		err = errors.New("请拖动滑块验证")
		return
	}

	newGeetest := NewGeeTest(config.C.Geetest.CaptchId, config.C.Geetest.PrivateKey)
	session, _ := store.Get(c.Request, sessionName)
	geetestType := session.Values["validType"]
	if geetestType == ValidateTypeSucc {
		result = newGeetest.SuccessValidate(params.Challenge, params.Validate, params.Seccode, clientType)
	} else {
		result = newGeetest.SuccessValidate(params.Challenge, params.Validate, params.Seccode, clientType)
		//result = newGeetest.FailValidate(params.Challenge, params.Validate, params.Seccode)
	}
	if !result {
		err = errors.New("滑动验证失败")
		return
	}
	return
}
